package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RemoveItemFromCartServlet extends HttpServlet {
    public static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    public static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private String workingItemId;
    private Cart cart;
    private LogService logService;
    private Account account;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        workingItemId = request.getParameter("workingItemId");
        HttpSession session = request.getSession();
        cart = (Cart)session.getAttribute("cart");

        Item item = cart.removeItemById(workingItemId);
        account = (Account)session.getAttribute("account");
        if (account != null){
            logService = new LogService();
            logService.insertLog("Remove Item from Cart","Item:"+workingItemId, account.getUsername());
        } else {
            logService = new LogService();
            logService.insertLog("Remove Item from Cart","Item:"+workingItemId, "null");
        }
        if (item == null) {
            session.setAttribute("message","Attemped to remove null CartItem from cart");
            request.getRequestDispatcher(ERROR).forward(request,response);
        }else{
            request.getRequestDispatcher(VIEW_CART).forward(request,response);
        }
    }
}
